package com.flybutter.usagelab.ui.home

import android.app.usage.UsageStatsManager
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.flybutter.usagelab.R
import com.flybutter.usagelab.databinding.ActivityUsageDetailBinding
import com.flybutter.usagelab.repository.UsageInfoDao
import com.flybutter.usagelab.repository.getAppDataBase
import com.flybutter.usagelab.service.queryUsageData
import com.flybutter.usagelab.utils.getFiled
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.ValueFormatter
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter

class UsageDetailActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityUsageDetailBinding
    private lateinit var pName: String

    private lateinit var barChart: BarChart
    private lateinit var usageDetailList: RecyclerView
    private lateinit var usageInfoDao: UsageInfoDao

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityUsageDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbar)
        pName = intent.getStringExtra("packageName")!!

        barChart = findViewById(R.id.usage_barchart)
        usageDetailList = binding.usageDetailList

        usageInfoDao = getAppDataBase().getUseStateDao()
        renderBarChartData()
        renderList()
    }

    fun renderBarChartData(){
        val sm = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
        val startTime = LocalDate.now().minusWeeks(1)
            .atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
        val statsList = sm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,System.currentTimeMillis())
            .filter { it.packageName == pName }
        barChart.xAxis.valueFormatter = object : ValueFormatter(){
            override fun getFormattedValue(value: Float): String {
                return LocalDate.now().minusDays((7 - value.toInt()).toLong()).format(
                    DateTimeFormatter.ofPattern("MM/dd")
                )
            }
        }
        barChart.description.isEnabled = false
        barChart.data = BarData(BarDataSet(statsList.mapIndexed{index,u->
             return@mapIndexed BarEntry((7-index).toFloat(),(u.totalTimeInForeground/1000/60).toFloat())
                                                               },""))
    }

    fun renderList(){
        usageDetailList.layoutManager = LinearLayoutManager(this)
        val sm = getSystemService(Context.USAGE_STATS_SERVICE)
            as UsageStatsManager
        class TempViewHolder(view: View): RecyclerView.ViewHolder(view)
        val list = sm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,0,
            System.currentTimeMillis()
        ).filter { it.packageName == pName }
        usageDetailList.adapter = object : RecyclerView.Adapter<TempViewHolder>(){
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TempViewHolder {
                val view = LayoutInflater.from(this@UsageDetailActivity)
                    .inflate(R.layout.compoent_usage_detail_item,usageDetailList,false)
                return TempViewHolder(view)
            }

            override fun onBindViewHolder(holder: TempViewHolder, position: Int) {
                val usageStats = list[position]
                val start =LocalDateTime.ofInstant(Instant.ofEpochMilli(usageStats.firstTimeStamp), ZoneId.systemDefault())
                val end =  LocalDateTime.ofInstant(Instant.ofEpochMilli(usageStats.lastTimeStamp), ZoneId.systemDefault())
               (holder.itemView.findViewById<TextView>(R.id.usage_count)).text =
                    "${usageStats.getFiled<Int>("appLaunchCount")}"
                holder.itemView.findViewById<TextView>(R.id.usage_length).text =
                    (usageStats.totalTimeInForeground/1000/60).toString()
                holder.itemView.findViewById<TextView>(R.id.date_textview).text =
                    start.toLocalDate().format(DateTimeFormatter.ofPattern("MM/dd"))
            }

            override fun getItemCount(): Int {
                return list.size
            }
        }
    }



}